package com.shanzmoo.platform.server.api.filter;

import cn.hutool.core.util.StrUtil;
import com.shanzmoo.base.bean.SResponse;
import com.shanzmoo.base.constant.ErrorCode;
import com.shanzmoo.base.util.SResponseUtils;
import com.shanzmoo.platform.server.api.manager.JwtManager;
import com.shanzmoo.platform.server.api.manager.MerchantInfoManage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: Gzhao 2020/11/9
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private final JwtManager jwtManager;
    private final MerchantInfoManage merchantInfoManage;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String headerToken = jwtManager.getJwtFromRequest(request);
        log.info("uri: {}, headerToken: {}", request.getRequestURI(), headerToken);
        if (StrUtil.isNotBlank(headerToken)
                && !"/auth/login".equals(request.getRequestURI())) {
            try {
//                String username = jwtManager.getUsernameFromJWT(headerToken);
                String username = "1111";
                UserDetails user = merchantInfoManage.findByUserName(username);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            } catch (Exception e) {
                log.error("spring security 校验异常", e);
                SResponseUtils.outputJson(response, SResponse.fail(ErrorCode.JWT_VALIDATE_FAIL));
                return;
            }
        }
        filterChain.doFilter(request, response);
    }
}
